package com.minimalist.lindi.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpStatus;
import com.minimalist.common.entity.basic.vo.file.FileVO;
import com.minimalist.common.entity.lindi.enums.LindiPurchaseApplicationFileTypeEnum;
import com.minimalist.common.entity.lindi.po.LindiPurchaseApplication;
import com.minimalist.common.entity.lindi.po.LindiPurchaseApplicationFile;
import com.minimalist.common.entity.lindi.po.LindiPurchaseApplicationProjectItem;
import com.minimalist.common.entity.lindi.po.LindiPurchaseApplicationTownItem;
import com.minimalist.common.entity.lindi.vo.purchaseapplication.LindiPurchaseApplicationVO;
import com.minimalist.common.entity.lindi.vo.purchaseapplicationfile.LindiPurchaseApplicationFileVO;
import com.minimalist.common.entity.lindi.vo.purchaseapplicationprojectitem.LindiPurchaseApplicationProjectItemVO;
import com.minimalist.common.entity.lindi.vo.purchaseapplicationtownitem.LindiPurchaseApplicationTownItemVO;
import com.minimalist.common.feign.client.basic.FileFeignClient;
import com.minimalist.common.response.R;
import com.minimalist.common.utils.UnqIdUtil;
import com.minimalist.lindi.mapper.LindiPurchaseApplicationFileMapper;
import com.minimalist.lindi.mapper.LindiPurchaseApplicationProjectItemMapper;
import com.minimalist.lindi.mapper.LindiPurchaseApplicationTownItemMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 购买申请管理器
 * 负责处理购买申请相关的复杂业务逻辑和关联数据操作
 *
 * @author 11987
 * @since 2025-01-23
 */
@Component
public class PurchaseApplicationManager{

    private static final Logger logger = LoggerFactory.getLogger(PurchaseApplicationManager.class);

    @Autowired
    private LindiPurchaseApplicationFileMapper purchaseApplicationFileMapper;

    @Autowired
    private LindiPurchaseApplicationProjectItemMapper purchaseApplicationProjectItemMapper;

    @Autowired
    private LindiPurchaseApplicationTownItemMapper purchaseApplicationTownItemMapper;

    @Autowired
    private FileFeignClient fileFeignClient;

    /**
     * 构建完整的购买申请VO对象，包含关联数据
     *
     * @param record 购买申请PO对象
     * @return 完整的购买申请VO对象
     */
    public LindiPurchaseApplicationVO buildCompleteVO(LindiPurchaseApplication record){
        // 转换基本信息
        LindiPurchaseApplicationVO vo = BeanUtil.copyProperties(record
                , LindiPurchaseApplicationVO.class);

        // 查询并设置关联的文件列表
        List<LindiPurchaseApplicationFile> fileList = purchaseApplicationFileMapper
                .selectFileListByPurchaseApplicationId(record.getPurchaseApplicationId());
        List<LindiPurchaseApplicationFileVO> fileVOList = BeanUtil.copyToList(fileList
                , LindiPurchaseApplicationFileVO.class);

        // 使用fileFeignClient查询文件详细信息
        if (fileVOList != null && !fileVOList.isEmpty()){
            fileVOList = fileVOList.stream().peek(fileVO -> {
                try{
                    R<FileVO> fileResult = fileFeignClient.getFileByFileId(fileVO.getFileId());
                    if (fileResult != null && fileResult.getCode() == HttpStatus.HTTP_OK
                            && fileResult.getData() != null){
                        fileVO.setFile(fileResult.getData());
                    }
                } catch (Exception e){
                    // 记录日志但不影响主流程
                }
            }).collect(Collectors.toList());
        }
        vo.setFileList(fileVOList);

        // 查询并设置关联的项目指标列表
        List<LindiPurchaseApplicationProjectItem> projectItemList =
                purchaseApplicationProjectItemMapper.selectProjectItemListByPurchaseApplicationId(
                        record.getPurchaseApplicationId());
        vo.setProjectItemList(BeanUtil.copyToList(projectItemList
                , LindiPurchaseApplicationProjectItemVO.class));

        // 查询并设置关联的镇街指标列表
        List<LindiPurchaseApplicationTownItem> townItemList =
                purchaseApplicationTownItemMapper.selectTownItemListByPurchaseApplicationId(
                        record.getPurchaseApplicationId());
        vo.setTownItemList(BeanUtil.copyToList(townItemList
                , LindiPurchaseApplicationTownItemVO.class));

        return vo;
    }

    /**
     * 保存关联数据
     *
     * @param vo 购买申请VO对象
     */
    public void saveRelatedData(LindiPurchaseApplicationVO vo){
        Long purchaseApplicationId = vo.getPurchaseApplicationId();

        // 保存文件关联数据
        if (vo.getFileList() != null && !vo.getFileList().isEmpty()){
            // 设置购买申请ID和审计字段
            vo.getFileList().forEach(file -> {
                file.setPurchaseApplicationId(purchaseApplicationId);
                file.setFileType(LindiPurchaseApplicationFileTypeEnum.ATTACHMENT.getCode());
                file.setCreateId(vo.getCreateId());
                file.setCreateTime(vo.getCreateTime());
                file.setUpdateId(vo.getUpdateId());
                file.setUpdateTime(vo.getUpdateTime());
            });
            List<LindiPurchaseApplicationFile> filePoList = BeanUtil.copyToList(
                    vo.getFileList(), LindiPurchaseApplicationFile.class);
            purchaseApplicationFileMapper.insertBatch(filePoList);
        }

        // 保存项目指标关联数据
        if (vo.getProjectItemList() != null && !vo.getProjectItemList().isEmpty()){
            // 设置购买申请ID和审计字段
            vo.getProjectItemList().forEach(item -> {
                item.setPurchaseApplicationId(purchaseApplicationId);
                item.setProjectId(UnqIdUtil.uniqueId());
                item.setCreateId(vo.getCreateId());
                item.setCreateTime(vo.getCreateTime());
                item.setUpdateId(vo.getUpdateId());
                item.setUpdateTime(vo.getUpdateTime());
            });
            List<LindiPurchaseApplicationProjectItem> projectPoList =
                    BeanUtil.copyToList(vo.getProjectItemList()
                            , LindiPurchaseApplicationProjectItem.class);
            purchaseApplicationProjectItemMapper.insertBatch(projectPoList);
        }

        // 保存镇街指标关联数据
        if (vo.getTownItemList() != null && !vo.getTownItemList().isEmpty()){
            // 设置购买申请ID和审计字段
            vo.getTownItemList().forEach(item -> {
                item.setPurchaseApplicationId(purchaseApplicationId);
                item.setTownItemId(UnqIdUtil.uniqueId());
                item.setCreateId(vo.getCreateId());
                item.setCreateTime(vo.getCreateTime());
                item.setUpdateId(vo.getUpdateId());
                item.setUpdateTime(vo.getUpdateTime());
            });
            List<LindiPurchaseApplicationTownItem> townPoList = BeanUtil.copyToList(
                    vo.getTownItemList(), LindiPurchaseApplicationTownItem.class);
            purchaseApplicationTownItemMapper.insertBatch(townPoList);
        }
    }

    /**
     * 删除关联数据
     *
     * @param purchaseApplicationId 购买申请ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteRelatedData(Long purchaseApplicationId){
        // 先查询文件关联数据，获取文件ID列表
        List<LindiPurchaseApplicationFile> fileList = purchaseApplicationFileMapper
                .selectFileListByPurchaseApplicationId(purchaseApplicationId);

        // 使用fileFeignClient删除文件信息
        if (fileList != null && !fileList.isEmpty()){
            for (LindiPurchaseApplicationFile file : fileList){
                try{
                    R<Void> result = fileFeignClient.deleteFile(file.getFileId());
                    if (result.getCode() != HttpStatus.HTTP_OK){
                        logger.warn("删除文件失败，fileId: {}, 错误信息: {}", file.getFileId(), result.getMessage());
                    }
                } catch (Exception e){
                    logger.warn("删除文件时发生异常，fileId: {}, 异常信息: {}", file.getFileId(), e.getMessage());
                }
            }
        }

        // 删除文件关联数据
        purchaseApplicationFileMapper.deleteFilesByPurchaseApplicationId(
                purchaseApplicationId);
        // 删除项目指标关联数据
        purchaseApplicationProjectItemMapper.deleteProjectItemsByPurchaseApplicationId(
                purchaseApplicationId);
        // 删除镇街指标关联数据
        purchaseApplicationTownItemMapper.deleteTownItemsByPurchaseApplicationId(
                purchaseApplicationId);
    }

    /**
     * 更新关联数据
     *
     * @param vo 购买申请VO对象
     */
    public void updateRelatedData(LindiPurchaseApplicationVO vo){
        Long purchaseApplicationId = vo.getPurchaseApplicationId();
        // 先删除原有的关联数据
        deleteRelatedData(purchaseApplicationId);
        // 再保存新的关联数据
        saveRelatedData(vo);
    }
}